import 'baseAuth.dart';
import 'interface.dart';

import 'package:cloudbase_core/cloudbase_core.dart';

class EmailAuthProvider extends AuthProvider {
  EmailAuthProvider(CloudBaseCore core) : super(core);

  Future<CloudBaseAuthState> signInByEmail(String email, String password) async {
    
    //通过邮箱登录
    CloudBaseResponse res = await CloudBaseRequest(core).postWithoutAuth(
      'auth.signIn',
      {'loginType': 'EMAIL', 'email': email, 'password': password});
    
    if (res == null) {
      throw new CloudBaseException(
          code: CloudBaseExceptionCode.NULL_RESPONES,
          message: "unknown error, res is null");
    }

    if (res.code != null) {
      throw new CloudBaseException(code: res.code, message: res.message);
    }

    if (res.data != null && res.data['refresh_token'] != null) {
      String newRefreshToken = res.data['refresh_token'];
      await setAuthType(CloudBaseAuthType.CUSTOM);
      await setRefreshToken(newRefreshToken);
      await refreshAccessToken();

      return CloudBaseAuthState(
          authType: CloudBaseAuthType.CUSTOM, refreshToken: newRefreshToken);
    } else {
      throw CloudBaseException(
          code: CloudBaseExceptionCode.AUTH_FAILED, message: '邮箱登录失败');
    }
  }
}